package com.swapper.json.spi.supports.time;

import com.swapper.json.*;

import java.lang.reflect.Type;
import java.time.Period;

/**
 * The {@link Period} wrapper factory.
 */
public enum PeriodWrapperFactory implements JsonWrapperFactory {
  INSTANCE;

  @SuppressWarnings("unchecked")
  @Override
  public <T> JsonWrapper<T> create(JsonContext context, Type type) {
    return type == Period.class ? (JsonWrapper<T>) Wrapper.INSTANCE : null;
  }

  public enum Wrapper implements JsonWrapper<Period> {
    INSTANCE;

    @Override
    public JsonValue wrap(Period value) {
      return value == null ? JsonValue.NULL : JsonString.valueOf(value.toString());
    }

    @Override
    public Period unwrap(JsonValue value) {
      return JsonValue.NULL.equals(value) ? null : Period.parse(value.toString());
    }
  }
}
